<template>
  <div>
     <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <!-- Alert 警告区 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false">
      </el-alert>
      <!-- steps 步骤条区 -->
      <el-steps :space="200" :active="activeName - 0" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs标签页区 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" :label-position="'top'">
      <el-tabs v-model="activeName" :tab-position="'left'" :before-leave="beforeTabsLeave" @tab-click="tabClicked">
        <el-tab-pane label="基本信息" name="0">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="addForm.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price">
            <el-input v-model="addForm.goods_price" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight">
            <el-input v-model="addForm.goods_weight" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_number">
            <el-input v-model="addForm.goods_number" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="handleChange">
              </el-cascader>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品参数" name="1">
          <el-form-item :label="item.attr_name" v-for="(item) in manyList" :key="item.id">
            <el-checkbox-group v-model="item.attr_vals">
              <el-checkbox :label="cb" v-for="(cb, i2) in item.attr_vals" :key="i2" border=""></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品属性" name="2">
           <el-form-item :label="item.attr_name" v-for="(item) in onlyList" :key="item.attr_id">
            <el-input v-model="item.attr_vals"></el-input>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品图片" name="3">
          <el-upload
            action="http://127.0.0.1:8888/api/private/v1/upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            list-type="picture"
            :headers="headersObj"
            :on-success="handleSuccess">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-tab-pane>
        <el-tab-pane label="商品内容" name="4">
          <!-- 富文本编辑器 -->
          <quill-editor v-model="addForm.goods_introduce"/>
          <el-button type="primary" class="addBtn" @click="addGoods">添加商品</el-button>
        </el-tab-pane>

      </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览会话框 -->
    <el-dialog
        :visible.sync="previewVisible"
        width="50%">
        <img :src="peviewPath" alt="" class="peviewImg">
      </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data () {
    return {
      activeName: '0', // 控制tabs标签页切换以及和steps 步骤调的联动
      addForm: { // 添加商品参数对象
        goods_name: '',
        goods_price: 1,
        goods_weight: 0,
        goods_number: 1,
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      addFormRules: { // 添加商品验证规则对象
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      cateProps: { // 商品分类级联选择器渲染规则
        expandTrigger: 'hover',
        label: 'cat_name',
        children: 'children',
        value: 'cat_id'
      },
      cateList: [], // 商品分类列表
      manyList: [], // 动态参数列表
      onlyList: [], // 静态属性列表
      headersObj: { // 图片上传设置请求头token
        Authorization: window.sessionStorage.getItem('token')
      },
      peviewPath: '', // 图片预览地址
      previewVisible: false // 图片预览会话框的显示或隐藏
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    async getCateList () { // 获取商品分类列表
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$msg.error('获取商品参数列表失败')
      this.cateList = res.data
      console.log(this.addForm.goods_cat)
    },
    handleChange (val) { // 商品分类级联选择器选项发生改变触发的事件
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
        return
      }
      console.log(this.addForm.goods_cat)
    },
    beforeTabsLeave (activeName, oldActiveName) { // 切换tabs标签页 触发的钩子函数
      if (this.addForm.goods_cat.length !== 3) {
        this.$msg.error('请选择商品分类')
        return false
      }
    },
    async tabClicked () { // 标签页切换时触发的函数
      if (this.activeName === '1') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'many' } })

        if (res.meta.status !== 200) return this.$msg.error('获取动态参数失败')
        console.log(res)
        res.data.forEach(item => {
          if (item.attr_vals) { item.attr_vals = item.attr_vals.split(' ') } else {
            item.attr_vals = []
          }
        })
        this.manyList = res.data
      } else if (this.activeName === '2') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } })

        if (res.meta.status !== 200) return this.$msg.error('获取动态参数失败')
        this.onlyList = res.data
      }
    },
    handlePreview (file) { // 图片上传预览函数
      this.previewVisible = true
      this.peviewPath = file.response.data.url
    },

    handleRemove (file) { // 图片上传 删除函数
      const removePath = file.response.data.tmp_path
      const i = this.addForm.pics.findIndex(x => {
        x.pic = removePath
      })
      this.addForm.pics.splice(i, 1)
      console.log(this.addForm.pics)
    },
    handleSuccess (response) { // 图片上传成功函数
      console.log(response.data.tmp_path)
      const picsInfo = { pic: response.data.tmp_path }
      this.addForm.pics.push(picsInfo)
      console.log(this.addForm.pics)
    },
    addGoods () { // 添加商品
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$msg.error('请填写必要参数')
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        // 处理动态参数
        this.manyList.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals.join(' ') }
          this.addForm.attrs.push(newInfo)
        })
        console.log(this.manyList)
        // 处理静态属性
        this.onlyList.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          this.addForm.attrs.push(newInfo)
        })
        form.attrs = this.addForm.attrs
        console.log(form)
        // 发送请求添加商品
        const { data: res } = await this.$http.post('goods', form)
        console.log(res)
        if (res.meta.status !== 201) return this.$msg.error('添加商品失败！')
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    cateId () { // 三级分类id
      if (this.addForm.goods_cat.length === 3) return this.addForm.goods_cat[2]
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.el-steps {
  margin: 20px 0;
}
.el-checkbox  {
  margin: 0 10px 0 0 !important;
}
.peviewImg {
  width: 100%;
}
.addBtn {
  margin-top: 15px;
}
</style>
